package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;

@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result listWithRedis() {
        //1.查询redis
        List<String> list = stringRedisTemplate.opsForList().range(CACHE_SHOPTYPE_KEY, 0, -1);
        //1.命中, 返回
        if (list  != null && list.size() != 0){
            //反序列化
            List<ShopType> shopTypes = list.stream().map((item) -> JSONUtil.toBean(item, ShopType.class))
                    .collect(Collectors.toList());
            return Result.ok(shopTypes);
        }
        //2.未命中, 查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //3.数据库未命中, 返回404
        if (shopTypes == null || shopTypes.size() == 0){
            return Result.fail("未查询到分类");
        }
        //4.数据库命中, 序列化存入redis
        List<String> shopTypesJson = shopTypes.stream()
                .map(JSONUtil::toJsonStr).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOPTYPE_KEY, shopTypesJson);
        //5.返回命中结果
        return Result.ok(shopTypes);
    }
}
